package com.kingint.web.portal.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kingint.mbg.bas.entity.BasWarrantyItems;
import com.kingint.mbg.bas.mapper.BasWarrantyItemsMapper;
import com.kingint.mbg.sys.entity.UmsMember;
import com.kingint.web.portal.base.service.WarrantyItemsService;
import com.kingint.web.sys.service.UmsAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WarrantyItemsServiceImpl implements WarrantyItemsService {

    @Resource
    private UmsAdminService adminService;
    @Resource
    private BasWarrantyItemsMapper warrantyItemsMapper;

    @Override
    public List<BasWarrantyItems> warrantyItemsList() {
        UmsMember currentMember = adminService.getCurrentMember();
        Integer hotelId = currentMember.getHotelId();
        if (StringUtils.isEmpty(hotelId)) {
            log.debug("该账号没有关联酒店id");
            return null;
        }
        QueryWrapper<BasWarrantyItems> wrapper = new QueryWrapper<>();
        wrapper.eq("hotel_id", hotelId)
                .eq("status", 0);
        List<BasWarrantyItems> warrantyItems = warrantyItemsMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(warrantyItems)) {
            //父类菜单
            List<BasWarrantyItems> collect = warrantyItems.stream().filter(s -> s.getPid() == 0).collect(Collectors.toList());
            cancelWarrantyItems(collect,warrantyItems);
            return collect;
        }
        return null;
    }

    private void cancelWarrantyItems(List<BasWarrantyItems> aClass, List<BasWarrantyItems> allList) {
        if (!CollectionUtils.isEmpty(aClass)) {
            //为一级菜单设置子菜单
            for (BasWarrantyItems info : aClass) {
                getChildList(info, allList);
            }
        }
    }

    private void getChildList(BasWarrantyItems info, List<BasWarrantyItems> aClass) {
        List<BasWarrantyItems> serviceClass = info.getWarrantyItems();
        if (CollectionUtils.isEmpty(serviceClass)) {
            serviceClass = new ArrayList<>();
        }
        for (BasWarrantyItems ser : aClass) {
            if (ser.getPid() == info.getId()) {
                serviceClass.add(ser);
            }
        }
        //递归查询
        if (serviceClass.size() != 0) {
            for (BasWarrantyItems child : serviceClass) {
                getChildList(child, aClass);
            }
        }
        info.setWarrantyItems(serviceClass);
    }
}
